from flask import Flask,jsonify,render_template,request,escape
from api import geocode,walking
import pandas as pd

key="2c5e812a00f3d177e589bd4162b15249"

app = Flask(__name__)


# 调用日志记录函数
def log_request(req:'flask_request',res:str)->None:
	with open('view.log','a') as log:
		print(req.form,req.remote_addr,req.user_agent,res,file=log,sep='|')

@app.route('/')
def shouye() ->'html':
	return render_template('first.html',the_title='兴兴子服务系统')

@app.route('/login',methods=['POST'])
def login_page() -> 'html':
	return render_template('login.html',the_title ="兴兴子服务系统")

@app.route('/shouye_xianshi',methods=['POST'])
def gongnengye() ->'html':
	return render_template('shouye_xianshi.html',the_title='兴兴子服务系统')


# 调用高德api——geocode,walking，数据返回gongnengye
@app.route('/ob',methods=['POST'])
def gongneng():
	address_origin = request.form['address_one']
	origin = geocode(key,address_origin)
	address_destination = request.form['address_two']
	destination = geocode(key,address_destination)
	
	results = walking(key,origin,destination)['route']['paths'][0]['steps']
	daohang = []
	for i in results:
		daohang.append(i['instruction'])
	return render_template('gongnengye.html',res=daohang,the_title='步行导航：',)

# POI搜索，点击“搜索”后，调用高德api——geocode和around，数据返回POI2
@app.route('/addlogin',methods=['POST'])
def addlogin() -> 'html':
	return render_template('POI1.html',the_title ="欢迎使用POI搜索功能！")

@app.route('/search',methods=['POST'])
def go_search():
	address = request.form['address']
	codes = geocode(address)

	location = codes
	types = request.form['types']
	results = around(location,types)['pois']


	names = []
	address2 = []
	for i in results:
		names.append(i['name'])
		address2.append(i['address'])
	combine = dict(zip(names,address2))

	log_request(request,results)
	return render_template('POI2.html',res=combine,the_title='为您返回的结果：')

# 静态地图
@app.route("/jintaiditu",methods=['GET'])
def jintaiditu():
	return render_template("ditu.html")

@app.route("/static_map",methods=['POST'])
def static_map():
	address = request.form['static_map']
	codes = geocode(address)
	results = "https://restapi.amap.com/v3/staticmap?location=%s&zoom=14&size=300*300&key=030d60847cc2dbf652a0d1f7e0fce690"%(codes)
	return render_template('ditu.html',res=results,the_title='为您获取的地图：')


# 查看日志
@app.route('/viewlog')
def view_the_log() ->'html':
	contents = []
	with open('vsearch.log') as log:
		for line in log:
			contents.append([])
			for item in line.split('|'):
				contents[-1].append(escape(item))
	titles = ('Form Data','Remote_addr','User_agent','Results')
	return render_template('viewlog.html',
		the_title='View Log',
		the_row_titles=titles,
		the_data=contents,)

app.run(debug=True)